<template>
  <div class="detail-box">
    <el-card>
      <!-- 文章标题 -->
      <div slot="header" class="clearfix">
        <h1>{{ detailInfo.title }}</h1>
      </div>
      <!-- 文章内容 -->
      <div v-html="detailInfo.content"></div>
    </el-card>
    <!-- 分层 -->
    <p class="line"></p>
    <!-- 评论 -->
    <el-card>
      <!-- 标题 -->
      <div slot="header" class="clearfix">
        <p>评论</p>
      </div>
      <!-- 评论内容 -->
      <div class="comment">
        <el-input v-model="commentValue" placeholder="请输入评论内容" />
        <el-button @click="sendComment">发送</el-button>
      </div>
      <div class="comment-list">
        <div v-for="(item, idx) in commentList" :key="idx" class="comment-item">
          <el-avatar :src="item.userimg" />
          <div class="comment-info">
            <span>{{item.username}}</span>
            <p>{{item.content}}</p>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { apigetDetail } from "@/api";
import { mapState } from "vuex";
export default {
  sockets: {
    connect: () => {
      console.log("连接成功");
    },

    // 获取socket返回值
    comment(res) {
      this.commentList = res.reverse();
    },
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  data() {
    return {
      commentList: [],
      detailInfo: {},
      commentValue: "",
    };
  },
  created() {
    this.getDetail();
  },
  methods: {
    getDetail() {
      apigetDetail({ id: this.$route.params.id * 1 }).then((res) => {
        // 将获取到的详情信息 保存到当前页面
        this.detailInfo = res.data;
      });
    },
    // 发送评论
    sendComment() {
      // 同时socket 给后端主动发送请求
      console.log(this.$socket)
      this.$socket.emit("chat", {
        socketId: this.$socket.id,
        content: this.commentValue, // 评论的内容
        userid: this.userInfo.id, // 评论的用户id
        username: this.userInfo.name, // 评论的用户名称
        userimg: this.userInfo.img, // 评论的用户头像
        articleId: this.$route.params.id, // 当前文章的id 
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.detail-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.line {
  padding: 10px;
}

.comment {
  display: flex;
}
.comment-list {
  width: 100%;
  display: flex;
  flex-direction: column;
  .comment-item {
    display: flex;
    padding: 10px;
    border-bottom: 1px solid #ccc;
    .comment-info {
      padding-left: 20px;
      span {
        font-size: 13px;
        color: #ccc;
      }
      p {
        font-size: 19px;
        padding: 5px 5px 5px 0;
      }
    }
  }
}
</style>